package com.backstage.common.uitil;

import com.backstage.common.constant.Constant;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.request.DelFileRequest;
import com.qcloud.cos.request.UploadFileRequest;
import com.qcloud.cos.sign.Credentials;
import org.json.JSONObject;

/**
 * @TODO 腾讯云文件存储工具类
 * @Author:阮雪峰
 * @Date：2017/8/6 14:19
 * @pagekage: com.backstage.common.util
 * @project: authority
 */
public class TxYunUtil {

    // 初始化秘钥信息
    private static Credentials cred = null;
    // 初始化客户端配置
    private static ClientConfig clientConfig = null;

    private static COSClient cosClient = null;

    private TxYunUtil(){}

    static {
        cred = new Credentials(Constant.APPID, Constant.TXYUN_SECRETID, Constant.TXYUN_SECRETKEY);
        clientConfig = new ClientConfig();
        // 设置bucket所在的区域，比如华南园区：gz； 华北园区：tj；华东园区：sh ；
        clientConfig.setRegion("tj");
        // 初始化cosClient
        cosClient = new COSClient(clientConfig, cred);
    }

    /**
     * 文件上传
     * @param fileName 文件名
     * @param dir 目录
     * @param bytes 文件字节数组
     * @return {'code':\$code, 'message':$mess, 'data':\$data}, code为0表示成功, message为SUCCESS或者失败原因
     */
    public static String uploadFile(String fileName, String dir, byte[] bytes){
        UploadFileRequest uploadFileRequest = new UploadFileRequest(Constant.BUCKETNAME, "/"+dir+"/"+fileName, bytes);
        JSONObject result = JsonUtil.strJsonToJSONObject(cosClient.uploadFile(uploadFileRequest));
        long code = new Long(result.get("code").toString());
        if(code == 0){
            JSONObject data = (JSONObject)result.get("data");
            return data.get("source_url").toString();
        }else {
            return "";
        }
    }

    /**
     * 删除文件
     * @param fileName 文件名
     * @param dir 目录
     * @return {'code':\$code, 'message':$mess}, code为0表示成功, message为SUCCESS或者失败原因
     */
    public static void delFile(String fileName, String dir){
        DelFileRequest delFileRequest = new DelFileRequest(Constant.BUCKETNAME, "/"+dir+"/"+fileName);
        cosClient.delFile(delFileRequest);
    }

    /*public static void main(String[] args) {
        try {
            String dir = "C:\\Users\\admin\\Desktop\\001.jpg";
            File file = new File(dir);
            byte[] bytes = CommonFileUtils.getFileContentByte(new FileInputStream(file), 0, (int) file.length());
            System.err.println(uploadFile("001.jpg", "img", bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
